package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient iScheduleClient;

    @Autowired
    private WmNewsAutoService wmNewsAutoService;



    @Override
    @Async
    public void newsToTask(WmNews wmNews) {
        Task task = new Task();
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (wmNews.getPublishTime()==null){
            wmNews.setPublishTime(new Date());
        }
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        iScheduleClient.addTask(task);
    }


    @Scheduled(cron = "0/1 * * * * ? ")
    @Override
    public void listener(){
        ResponseResult taskResult = iScheduleClient.poll
                (TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        if (taskResult.getData()!=null){
            String json_str = JSON.toJSONString(taskResult.getData()); //json
            Task task = JSON.parseObject(json_str, Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            log.info("收到的信息为{}",wmNews);
            wmNewsAutoService.disposeNews(wmNews);
        }

    }
}
